package com.chen.sample2.common.util;

import lombok.extern.slf4j.Slf4j;

import java.io.PrintWriter;
import java.io.StringWriter;

/**
 * 获取异常的堆栈信息
 */
@Slf4j
public final class ExceptionUtil {

    private ExceptionUtil(){}
    /**
     * 获取异常的堆栈信息 stackTrace
     */
    public static String getStackTrace(Throwable e) {
        String swStr = null;
        try (StringWriter sw = new StringWriter(); PrintWriter pw = new PrintWriter(sw)) {
            e.printStackTrace(pw);
            pw.flush();
            sw.flush();
            swStr = sw.toString();
        } catch (Exception ex) {
            log.error("错误输出出错：{}",ex.getMessage());
        }
        return swStr;
    }

    public static void main(String[] args) {
        System.out.println(getStackTrace(new NullPointerException()));
    }
}
